<?php

declare(strict_types=1);

namespace app\utils\image;

use Dsxwk\Framework\WebmanHelper\Redis\Redis;
use Gregwar\Captcha\CaptchaBuilder;
use Gregwar\Captcha\PhraseBuilder;

class Code
{
    /**
     * 构建验证码
     *
     * @param int    $width
     * @param int    $height
     * @param int    $length
     * @param string $charset
     * @param int    $ttl
     *
     * @return array
     */
    public static function build(int $width = 120, int $height = 50, int $length = 4, string $charset = '0123456789', int $ttl = 300): array
    {
        $key = uniqid('captcha_', true);

        $phraseBuilder = new PhraseBuilder($length, $charset);
        $builder       = new CaptchaBuilder(null, $phraseBuilder);
        $builder->build($width, $height);

        Redis::set($key, strtolower($builder->getPhrase()), expireTTL: $ttl);

        return [
            'key'   => $key,
            'image' => $builder->inline()
        ];
    }

    /**
     * 验证码校验
     *
     * @param string $key
     * @param string $code
     *
     * @return bool
     */
    public static function verify(string $key, string $code): bool
    {
        $cached = Redis::get($key);
        if ($cached && strtolower($code) === $cached) return true;

        return false;
    }
}